import * as _ from "lodash";
function request(url: string, method: "GET" | "PUT" | "DELETE" | "POST", data?: any, headers?: any): Promise<any> {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: url,
      dataType: "json",
      type: method,
      data: data,
      headers: headers,
      success: function (res) {
        resolve(res);
      },
      error: function (error) {
        reject(error);
      }
    })
  })
}


const jsonType = { 'Content-Type': 'application/json' };

export function createSerialNumber(prefix: string) {
  return request("/serialnumbers", "POST", { prefix })
}


export function createProudctInfo(productInfo) {
  return request("/proudcts", "POST", JSON.stringify(productInfo), jsonType);
}

export function getProductClasses() {
  return request("/productclasses", "GET");
}

export function createProductClass(parentId, text) {
  const playload = JSON.stringify({ parent_id: parentId, text: text });
  return request("/productclasses", "POST", playload, jsonType);
}

export function updateProductClass(productClass) {
  const playload = JSON.stringify(productClass);
  return request(`/productclasses/${productClass.id}`, "PUT", playload, jsonType);
}


export function getUnits() {
  return request("/units", "GET");
}

export function createUnit(unit) {
  return request("/units", "POST", JSON.stringify(unit), jsonType);
}

export function deleteUnit(unit) {
  const units = _.isArray(unit) ? unit : [unit]
  return request(`/units/${JSON.stringify(units.map(_unit => _unit.id))}`, "DELETE")
}